import { Component, Input, OnInit } from "@angular/core";
import { FormBuilder, FormGroup, Validators } from "@angular/forms";

import { ModalController } from "@ionic/angular";

import * as CryptoJS from 'crypto-js';

import { ChooseCityComponent } from "./../choose-city/choose-city.component";
import { CustomValidators } from "../../shared/custom-validators/custom-validators";
import { AppGlobalService } from "../../shared/service/app-global.service";
import { EventService } from "../../shared/service/event.service";
import { HttpService } from "../../shared/service/http.service";
import { MapBaiduService } from "../../shared/service/map.baiduapi";
declare const Umeng;
@Component({
  selector: "app-register",
  templateUrl: "./register.component.html",
  styleUrls: ["./register.component.scss", "../login/login.component.scss"]
})
// tslint:disable
export class RegisterComponent implements OnInit {
  constructor(
    private modalCtrl: ModalController,
    private fb: FormBuilder,
    private http: HttpService,
    private appGlobalService: AppGlobalService,
    private mapBaiduService: MapBaiduService,
    private eventService: EventService
  ) { }
  @Input() tagData: any = {};
  sessionId: string;
  open: boolean;
  registerForm: FormGroup;
  mobileNum: any;
  mvcodeNum: any;
  usernameNum: any;
  passwordNum: any;
  passwordNum1: any;
  invitationCode: any;
  open1: any;
  positionInfo: any;
  cityId: any;
  cityName: any;
  time = -1;
  text = "获取验证码";
  mvcode: any;
  appTypeCustom: any;
  disableBtn = false;
  isCheckRead = false;
  ngOnInit() {
    const bodyStyles = window.getComputedStyle(document.body);
    this.appTypeCustom = bodyStyles.getPropertyValue('--appTypeCustom').trim().replace('"', '').replace('"', '');
    this.sessionId = localStorage.getItem("sessionId");
    const parttern = "[A-Za-z0-9]{6,12}";
    let mobile =
      localStorage.getItem("loginAccount") &&
        localStorage.getItem("loginAccount") !== "undefined"
        ? localStorage.getItem("loginAccount")
        : "";
    if (mobile && mobile.length > 11) {
      mobile = '';
    }
    this.registerForm = this.fb.group({
      account: [
        "",
        [
          Validators.required,
          Validators.minLength(11),
          Validators.maxLength(11),
          CustomValidators.phone
        ]
      ],
      mvcode: ["", [Validators.required, CustomValidators.vcode]],
      invitationCode: ["", [Validators.minLength(6)]],
      password: [
        "",
        [
          Validators.required,
          Validators.minLength(6),
          Validators.maxLength(12),
          Validators.pattern(parttern)
        ]
      ],
      // password1: [
      //   "",
      //   [
      //     Validators.required,
      //     Validators.minLength(6),
      //     Validators.maxLength(12),
      //     Validators.pattern(parttern)
      //   ]
      // ]
    });
    const that = this;
    setTimeout(() => {
      that.positionInfo = JSON.parse(
        this.mapBaiduService.getStore("locationObj")
      )
        ? JSON.parse(this.mapBaiduService.getStore("locationObj"))
        : that.gotoPage();
    }, 500);
    this.mobileNum = mobile;
  }
  getErrors() {
    if (this.registerForm.controls.account.errors) {
      if (this.registerForm.controls.account.errors.required) {
        this.appGlobalService.showToast("请输入手机号码", 3000, "top");
      } else {
        this.appGlobalService.showToast("请输入正确的手机号码", 3000, "top");
      }
    } else if (this.registerForm.controls.mvcode.errors) {
      if (this.registerForm.controls.mvcode.errors.required) {
        this.appGlobalService.showToast("请输入验证码", 3000, "top");
      } else {
        this.appGlobalService.showToast("请输入正确的验证码", 3000, "top");
      }
    } else if (this.registerForm.controls.password.errors) {
      if (this.registerForm.controls.password.errors.required) {
        this.appGlobalService.showToast("请输入密码", 3000, "top");
      } else {
        this.appGlobalService.showToast("请输入正确的密码", 3000, "top");
      }
    } else if (this.registerForm.controls.invitationCode.errors) {
      {
        this.appGlobalService.showToast("请输入正确的邀请码", 3000, "top");
      }
    }
    // else if (this.registerForm.controls.password1.errors) {
    //   if (this.registerForm.controls.password1.errors.required) {
    //     this.appGlobalService.showToast("请再次输入密码", 3000, "top");
    //   } else {
    //     this.appGlobalService.showToast("请输入正确的密码", 3000, "top");
    //   }
    // } 
  }
  submit() {
    if (this.isCheckRead === false) {
      this.appGlobalService.showToast('请先同意用户协议及隐私政策再继续使用APP', 2000, 'top');
      return;
    }
    if (this.registerForm.status === "INVALID") {
      this.getErrors();
      return;
    }
    // else if (this.passwordNum1 !== this.passwordNum) {
    //   this.appGlobalService.showToast("两次输入的密码不一致", 3000, "top");
    //   return;
    // }
    // 禁止用户重复提交
    this.disableBtn = true;
    const param = {
      content: Object.assign(this.registerForm.value),
      id: this.tagData.sureButton.id,
      sessionId: this.sessionId
    };
    this.tagData.sureButton.actionElement.param.map(item => {
      param.content[item.name] = item.value;
    });
    // 重新赋值
    param.content.password = this.appGlobalService.encryptDes(this.passwordNum);
    // param.content.password1 = this.appGlobalService.encryptDes(this.passwordNum1);
    // 用户注册城市
    param.content.city_id = JSON.parse(this.mapBaiduService.getStore("position")).code;
    this.http.post("application/submit", param, data => {
      if (data.success) {
        this.appGlobalService.showToast("注册成功", 3000, "top");
        if (data.data && data.data.user_id) {
          localStorage.setItem("userId", data.data.user_id);
          // 注册成功后 记录友盟事件
          this.appGlobalService.initUmengEventWithParameters("enter_app_with_registerAccount_event");
          localStorage.setItem("onRegisterWebSocketTag", "1");
          this.eventService.eventEmit.emit("onRegisterWebSocket", data.data.user_id);
        }
        const loginObj = {
          pageId: data.target,
          params: {},
          sessionId: this.sessionId
        };
        localStorage.setItem("needRefreshTab1", "true");
        localStorage.setItem("needRefreshTab2", "true");
        localStorage.setItem("needRefreshTab3", "true");
        localStorage.setItem("needRefreshTab4", "true");
        localStorage.setItem("needRefreshTab5", "true");
        this.appGlobalService.goToForward(loginObj);
      } else {
        this.appGlobalService.showToast(data.message, 3000, "top");
      }
      this.disableBtn = false;
    });
  }
  getCity() {
    const city = localStorage.getItem("currentCityPosition");
    this.cityId = JSON.parse(city).id;
    console.log(this.cityId, "cityid");
  }
  goToLogin() {
    const loginObj = {
      pageId: this.tagData.login.link.target,
      params: {},
      sessionId: this.sessionId
    };
    this.appGlobalService.goToForward(loginObj);
  }
  async gotoPage() {
    const that = this;
    const modal = await this.modalCtrl.create({
      component: ChooseCityComponent,
      componentProps: {
        value: this.tagData.position.link.target,
        modalTitle: "选择城市"
      }
    });
    modal.onDidDismiss().then(data => {
      const value = data.data;
      that.cityId = value.i;
      that.cityName = value.n;
    });
    return await modal.present();
  }
  getVC(invalid) {
    console.log(this.registerForm.get("account"));
    if (invalid) {
      this.appGlobalService.showToast("请输入正确手机号码", 3000, "top");
    } else {
      const params = {
        content: {
          mobile: this.registerForm.value.account
        },
        id: this.tagData.codeButton["id"],
        sessionId: localStorage.getItem("sessionId")
      };
      this.http.post("application/submit", params, data => {
        if (data.success) {
          this.appGlobalService.showToast(
            "验证码已发送、请注意查收",
            3000,
            "top"
          );
          if (data.data) {
            this.mvcode = data.data.mvcode;
          }
          this.time = 90;
          const timer = setInterval(() => {
            this.time = this.time - 1;
            if (this.time === -1) {
              clearInterval(timer);
              this.text = "获取验证码";
            }
          }, 1000);
        } else {
          this.appGlobalService.showToast(data.message, 3000, "top");
        }
      });
    }
  }
  async openArgument(e) {
    e.stopPropagation();
    this.eventService.eventEmit.emit("openPage",
      // tslint:disable-next-line:no-string-literal
      JSON.stringify({ type: 'url', urlLinkTitle: "用户协议", target: window['appGlobalService'].serviceAgreementLink, params: {} }));
  }

  async alertPrivacyPolicy(e) {
    e.stopPropagation();
    // 跳转连接的两种方式 2023年9月5日
    // this.appGlobalService.openUrl("隐私权限","http://pay.fengwo168.com/staticH5/fengwo.html?hiddenTtitle=true");
    this.eventService.eventEmit.emit("openPage",
      JSON.stringify({ type: 'url', urlLinkTitle: "隐私权限", target: this.appGlobalService.privatePolicyLink, params: {} }));
  }

  openSettleIn(e) {
    e.stopPropagation();
    this.eventService.eventEmit.emit("openPage",
      JSON.stringify({ type: 'url', urlLinkTitle: "入驻协议", target: this.appGlobalService.settleInLink, params: {} }));
  }
  decryptByDES(ciphertext, key) {
    const keyHex = CryptoJS.enc.Utf8.parse(key);
    const decrypted = CryptoJS.DES.decrypt({
      ciphertext: CryptoJS.enc.Base64.parse(ciphertext)
    }, keyHex, {
      mode: CryptoJS.mode.ECB,
      padding: CryptoJS.pad.Pkcs7
    });
    return decrypted.toString(CryptoJS.enc.Utf8);
  }
  checkRead() {
    this.isCheckRead = !this.isCheckRead;
  }
}

